#!/usr/bin/env python
from PIL import Image   

# flatten a list of lists into a one-dimensional list
def flatten(z):
    return [item for sublist in z for item in sublist]

# normalize values in a list to fill the range between lower and upper
def normalize(L,lower,upper,maximum = None, minimum = None):
    lower, upper = map(float,(lower,upper))
    if minimum is None:
        minimum = min([min(l) for l in L])
    if maximum is None:
        maximum = max([max(l) for l in L])
    spread_in = maximum - minimum
    spread_out = upper - lower
    if spread_in != 0:
        return [[float(i)/spread_in*spread_out-minimum/spread_in*spread_out+lower for i in l] for l in L]
    else:
        return [[lower+upper/2 for i in l] for l in L]

# show the image in deafult viewer
def show_image(image):
    image = normalize(image,0.0,255.0)
    img = Image.new('L',(len(image[0]),len(image)))
    img.putdata(flatten(image))
    img.show()

# save the image (i.e. list of lists of floats)
# to the specified path (dont forget an extension!)
def save_image(image, path):
    image = normalize(image,0.0,255.0)
    img = Image.new('L',(len(image[0]),len(image)))
    img.putdata(flatten(image))
    img.save(path)

# load an image (i.e. list of lists of floats) from the specified path
def load_image(path):
    img = Image.open(path).convert("L")
    photo = img.load()
    photo = [[photo[i,j] for i in xrange(img.size[0])] for j in xrange(img.size[1])]
    photo = normalize(photo,-1.0,1.0,minimum = 0.0, maximum = 255.0)
    return photo